package com.hjw.dynamicdatasource.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ivan
 */
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {


    private final DynamicDataSourceManager dataSourceManager;

    public DynamicRoutingDataSource(DynamicDataSourceManager manager) {
        this.dataSourceManager = manager;
        // 关键：启动时就配置 targetDataSources（用默认数据源）
        DataSource defaultDataSource = manager.getDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("default", defaultDataSource);
        super.setTargetDataSources(targetDataSources);
        // 配置默认目标数据源
        super.setDefaultTargetDataSource(defaultDataSource);
    }

    @Override
    protected DataSource determineTargetDataSource() {
        DataSource currentDataSource = dataSourceManager.getDataSource();
        // 若数据源已更新（与默认数据源不同），则刷新 targetDataSources
        if (currentDataSource != super.getResolvedDefaultDataSource()) {
            Map<Object, Object> targetDataSources = new HashMap<>();
            targetDataSources.put("current", currentDataSource);
            super.setTargetDataSources(targetDataSources);
            super.setDefaultTargetDataSource(currentDataSource);
            super.afterPropertiesSet(); // 重新初始化
        }
        return super.determineTargetDataSource();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return "current";
    }
}